<template>
  <div class="container">
    <div class="companyTree">
      <div class="title">组织架构（外部单位）</div>
      <div class="tree">

        <el-input class="search" v-model="filterText" placeholder="" :prefix-icon="Search" />
        <el-tree ref="treeRef" class="filter-tree" :data="companyData" :props="defaultProps" default-expand-all
          :filter-node-method="filterNode" @node-click="handleNodeClick">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="oper">
                <img :src="image.rapCompanyAdd" @click="e => handleAppend(data, e)" v-if="node.level <= 3" />
                <img :src="image.rapCompanyEdit" @click="e => handleUpdate(data, e)" />
                <template v-if="node.children && node.children.length > 0">
                  <img v-if="node.level !== 1" :src="image.rapCompanyDelete" @click="handleRemove2" />
                </template>
                <template v-else>
                  <el-popconfirm v-if="node.level !== 1" title="是否删除?" confirmButtonText="确定" cancelButtonText="取消"
                    @confirm="handleRemove(data)">
                    <template #reference>
                      <img :src="image.rapCompanyDelete" />
                    </template>
                  </el-popconfirm>
                </template>
              </span>
            </span>
          </template>
        </el-tree>

      </div>
    </div>
    <div class="layout">
      <layout-card :filters="exampleOptions" headline="信息列表" @search-change="searchChange" @search-reset="searchReset">
        <template #action>
          <el-button type="primary" @click="() => openAddDialog()">添加成员</el-button>
        </template>

        <table-common :columns="exampleColumns" :loading="loading" :pagination="pager" :table-data="tableData"
          size="large" @current-change="currentChange" @size-change="sizeChange">
          <template #action="{ row }">
            <!-- <el-button class="link-btn" link type="primary" @click="() => openUpdateDialog(row)">编辑</el-button> -->
            <el-popconfirm title="是否删除?" confirmButtonText="确定" cancelButtonText="取消" @confirm="handleDelete(row)">
              <template #reference>
                <el-button class="link-btn" link type="danger">移出该组</el-button>
              </template>
            </el-popconfirm>
          </template>
        </table-common>
      </layout-card>
    </div>
  </div>

  <!-- 编辑部门 -->
  <EditCompany :visible="centerDialogVisible" :companyData="companyData" :isAdd="isAdd" :info="info"
    @cancel="handleCancel" @ok="handleOk" />

  <!-- 编辑人员 -->
  <Edit :visible="centerDialogVisible2" :info="info" :selectId="state.selectId" @cancel="handleCancel" @ok="handleOk" />
</template>
<script lang="ts" setup>
import { ref, watch, reactive, onBeforeMount, computed } from 'vue'
import { ElTree, ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { Search } from '@element-plus/icons-vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { repCompanyFindTree, repMemberFindpage, repCompanyDelete, repCompanyRemove } from '@/api/rep/company'
import { image } from '@/assets/index'
import { exampleColumns } from './config/columns'
import { getResource } from '@/api/resource'
import EditCompany from './editCompany.vue'
import Edit from './edit.vue'

interface CompanyState {

}

interface SearchType {
  memberName?: String;
  memberRole?: String;
}

interface Tree {
  [key: string]: any
}


const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
// 查询条件
const exampleOptions = ref([
  {
    label: '人员姓名',
    prop: 'memberName',
    type: 'input',
    defaultValue: '',
    inputProps: {
      clearable: true,
      placeholder: '请输入人员姓名'
    }
  },
  {
    label: '角色',
    prop: 'memberRole',
    type: 'select',
    defaultValue: '',
    inputProps: {
      options: [
        { label: '全部', value: '' },
      ]
    }
  },
])

const loading = ref(false)
const tableData = ref<CompanyState[]>([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0
})
const search = ref<SearchType>({
  memberName: '',
  memberRole: '',
})

const info = ref(null)
const isAdd = ref(false)
const centerDialogVisible = ref(false)
const centerDialogVisible2 = ref(false)

const companyData = ref<Tree[]>([])
const state = reactive({
  selectId: ''
})

const customNodeClass = (data: Tree, node: Node) => {
  if (data.companyId === state.selectId) {
    return 'is-penultimate'
  }
  return null
}

const defaultProps = {
  children: 'children',
  label: 'companyName',
  class: customNodeClass,
}

const deepFn = (arr = [], fn = (info: any, l: number) => { }, { level = 1, key = "children" }) => {
  arr.forEach((item: any) => {
    if (Array.isArray(item[key])) {
      deepFn(item[key], fn, { level: level + 1, key })
    }
    fn(item, level);
  })
}

/**
* 点击新增方法
*/
const openUpdateDialog = (row = null) => {
  centerDialogVisible2.value = true
  info.value = row
}

// 删除
const handleDelete = async (row: any) => {
  const res: any = await repCompanyRemove({
    companyId: row.companyId, memberId: row.memberId, lastMender: {
      id: userInfo.value.userId,
      name: userInfo.value.name,
      userName: userInfo.value.userName,
      organId: userInfo.value.organId || '',
      organName: userInfo.value.organName || ''
    }
  });
  if (res?.code === '1') {
    ElMessage.success('已移除！');
    findTree();
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

/**
* 打开编辑弹框
*/
const openAddDialog = (row = null) => {
  centerDialogVisible2.value = true
  info.value = row
}

/**
* 点击查询
*/
const searchChange = (data: FilterDataType) => {
  search.value = data
  loadData()
}

/**
* 点击重置
* @param data 数据
*/
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}

const loadData = async () => {
  loading.value = true
  const payload: any = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {}
  }
  if (state.selectId) {
    payload.condition.companyId = state.selectId || '';
  }
  if (search.value.memberName) {
    payload.condition.memberName = search.value.memberName || '';
  }
  if (search.value.memberRole) {
    payload.condition.memberRole = search.value.memberRole || '';
  }
  // ...获取数据
  const res: any = await repMemberFindpage(payload);
  loading.value = false
  if (res && res.code === '1') {
    tableData.value = res?.data?.list
    pager.total = res?.data?.total
    pager.pageCount = res?.data?.pages
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

// 修改每页条数
const sizeChange = (size: number) => {
  pager.pageSize = size
  loadData()
}

// 翻页
const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}

// 樹節點被點擊
const handleNodeClick = (data, node, treeNode, e: Event) => {
  state.selectId = data?.companyId || '';
  pager.currentPage = 1;
  loadData();
}

// 新增
const handleAppend = (data: any, e: Event) => {
  e.stopPropagation()
  e.preventDefault()
  isAdd.value = true;
  centerDialogVisible.value = true;
  info.value = data;
}

// 编辑
const handleUpdate = (data: any, e: Event) => {
  e.stopPropagation()
  e.preventDefault()
  isAdd.value = false;
  centerDialogVisible.value = true;
  info.value = data;
}

// 删除
const handleRemove = async (data: any) => {
  const res: any = await repCompanyDelete({
    companyId: data.companyId,
    lastMender: {
      id: userInfo.value.userId,
      name: userInfo.value.name,
      userName: userInfo.value.userName,
      organId: userInfo.value.organId || '',
      organName: userInfo.value.organName || ''
    }
  })
  if (res?.code === '1') {
    ElMessage.success("删除成功!")
    loadData();

    findTree();
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

const handleRemove2 = (e: Event) => {
  e.stopPropagation()
  e.preventDefault()
  ElMessage.warning('包含子级单位，不支持删除')
}

/**
* 弹窗点击取消
*/
const handleCancel = () => {
  centerDialogVisible.value = false
  centerDialogVisible2.value = false
}

/**
* 弹窗点击确认
*/
const handleOk = () => {
  centerDialogVisible.value = false
  centerDialogVisible2.value = false

  findTree();
}

const findTree = async () => {
  // if (!userInfo.value.respOrgId) {
  //   setTimeout(() => {
  //     findTree();
  //   }, 600);
  //   return
  // }
  const res = await repCompanyFindTree(userInfo.value.organName === 'TOC' ? { companyId: userInfo.value.respOrgId || '' } : {});
  console.log(res)

  deepFn(res?.data, (record: any, level: number) => {
    record.id = record.companyId;
    record.level = level;
    record.label = record.companyName;
    if (Array.isArray(record.memberList) && record.memberList.length) {
      record.memberList.forEach(ele => {
        if (!record.children) record.children = [];
        record.children.push({ ...ele, id: ele.memberId, level: level + 1, label: ele.memberName, isMember: true });
      })
    }
  }, { level: 1, key: 'children' })
  companyData.value = res?.data || [];
  if (!state.selectId) {
    state.selectId = companyData.value?.[0]?.companyId || ''
  }
  loadData();
}

const loadDict = () => {
  // 角色
  getResource('rep_member_role').then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        let list = res.data?.properties?.meta || []
        exampleOptions.value[1].inputProps.options = [
          { label: '全部', value: '' },
          ...list]
      }
    }
  })
}

onBeforeMount(() => {

  loadDict();

  findTree();
})


</script>

<style lang="less" scoped>
.container {
  display: flex;
  align-items: stretch;
  justify-content: center;
  background: #f5f7f9;
  min-height: 100%;
  overflow: hidden;

  .companyTree {
    padding: 24px;
    margin: 24px 0 24px 24px;
    background: #FFF;
    border-radius: 8px;
    width: 360px;

    .title {
      font-size: 16px;
      font-family: HarmonyOS_Sans_SC_Medium;
      color: #353A42;
      line-height: 24px;
      margin: 5px 0;

      &::after {
        content: '';
        display: block;
        margin: 16px 0;
        height: 1px;
        background: rgba(132, 139, 157, 0.16);
      }
    }

    .search {
      margin-bottom: 20px;
    }

    /deep/ .el-tree-node__content {
      height: 32px;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;

      .oper {
        display: flex;
        justify-content: center;
        align-items: center;
        user-select: none;

        img {
          width: 20px;
          height: 20px;
          object-fit: contain;

          &:hover {
            transform: scale(1.1);
          }
        }

        img+img {
          margin-left: 8px;
        }

        .border {
          border-radius: 4px;
          border: 1px solid #2F7DF1;
          padding: 2px;
          box-sizing: border-box;
          margin-left: 8px;
        }
      }
    }
  }

  .layout {
    flex-grow: 1;
  }
}
</style>
<style lang="less">
.el-tree-node__content:hover {
  background-color: #f5f7fa !important;
}

.is-penultimate {
  background: #f5f7fa !important;

  .el-tree-node__content:hover {
    background-color: #f5f7fa !important;
  }
}
</style>